'use client'

import { useState, useEffect } from 'react'
import { Card } from '@/components/ui/card'
import { DatePickerWithRange } from '@/components/DatePickerWithRange'
import { UserTrendChart } from './UserTrendChart'
import { Button } from '@/components/ui/button'
import type { DateRange } from 'react-day-picker'

type TimeRange = 'day' | 'week' | 'month' | 'custom'
type MetricType = 'newUsers' | 'activeUsers' | 'totalUsers'

interface CustomDateRange {
  from: Date
  to: Date
}

interface UserTrendData {
  newUsers: number
  activeUsers: number
  totalUsers: number
  date: string
}

const metricLabels = {
  newUsers: '新增用户数',
  activeUsers: '活跃用户数',
  totalUsers: '累计用户数',
}

const TIME_RANGES = [
  { value: 'day', label: '本日' },
  { value: 'week', label: '本周' },
  { value: 'month', label: '本月' },
  { value: 'custom', label: '自定义' },
]

export function UserTrendAnalysis() {
  const [timeRange, setTimeRange] = useState<TimeRange>('day')
  const [selectedMetrics, setSelectedMetrics] = useState<MetricType[]>(['newUsers'])
  const [dateRange, setDateRange] = useState<DateRange | undefined>()
  const [timeDescription, setTimeDescription] = useState<string>('')
  const [loading, setLoading] = useState(false)
  const [data, setData] = useState<UserTrendData[]>([])

  const toggleMetric = (metric: MetricType) => {
    setSelectedMetrics(prev => {
      if (prev.includes(metric)) {
        // 至少保留一个指标
        if (prev.length === 1) return prev
        return prev.filter(m => m !== metric)
      }
      return [...prev, metric]
    })
  }

  // 转换日期范围格式
  const getCustomDateRange = (): CustomDateRange | undefined => {
    if (dateRange?.from && dateRange?.to) {
      return {
        from: dateRange.from,
        to: dateRange.to
      }
    }
    return undefined
  }

  // 更新时间描述
  const updateTimeDescription = (newTimeRange: TimeRange, customRange?: DateRange) => {
    const today = new Date()
    let description = ''

    switch (newTimeRange) {
      case 'day':
        description = `${today.getFullYear()}年${today.getMonth() + 1}月${today.getDate()}日`
        break
      case 'week':
        const weekStart = new Date(today)
        weekStart.setDate(today.getDate() - 6)
        description = `${weekStart.getMonth() + 1}月${weekStart.getDate()}日 至 ${today.getMonth() + 1}月${today.getDate()}日`
        break
      case 'month':
        description = `${today.getFullYear()}年${today.getMonth() + 1}月1日 至 ${today.getMonth() + 1}月${today.getDate()}日`
        break
      case 'custom':
        if (customRange?.from && customRange?.to) {
          const fromDate = customRange.from.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' })
          const toDate = customRange.to.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' })
          description = `${fromDate} 至 ${toDate}`
        }
        break
    }

    setTimeDescription(description)
  }

  // 初始化时设置时间描述
  useEffect(() => {
    updateTimeDescription('day')
  }, [])

  const handleTimeRangeChange = (newTimeRange: TimeRange) => {
    setTimeRange(newTimeRange)
    updateTimeDescription(newTimeRange, dateRange)
  }

  return (
    <Card className="p-6">
      <div className="space-y-4">
        <div className="flex items-center justify-between">
          <h2 className="text-lg font-semibold">访问核心指标趋势</h2>
        </div>

        <Card className="p-6 shadow-lg">
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                {Object.entries(metricLabels).map(([metric, label]) => (
                  <Button
                    key={metric}
                    variant={selectedMetrics.includes(metric as MetricType) ? "default" : "outline"}
                    onClick={() => toggleMetric(metric as MetricType)}
                    className="shadow-sm hover:shadow-md transition-all duration-200"
                  >
                    {label}
                  </Button>
                ))}
              </div>

              <div className="flex items-center gap-4">
                <div className="flex items-center gap-2">
                  {TIME_RANGES.map(range => (
                    <Button
                      key={range.value}
                      variant={timeRange === range.value ? "default" : "outline"}
                      onClick={() => handleTimeRangeChange(range.value as TimeRange)}
                      className="shadow-sm hover:shadow-md transition-all duration-200"
                    >
                      {range.label}
                    </Button>
                  ))}
                </div>
                {timeRange === 'custom' && (
                  <div className="relative">
                    <DatePickerWithRange
                      value={dateRange}
                      onChange={(range) => {
                        setDateRange(range)
                        if (range?.from && range?.to) {
                          updateTimeDescription('custom', range)
                        }
                      }}
                    />
                  </div>
                )}
              </div>
            </div>
            {/* 时间范围显示 */}
            <div className="flex items-center pt-4 border-t border-gray-100">
              <div className="text-sm text-gray-500">
                当前数据范围：
                <span className="ml-2 text-gray-900 font-medium">{timeDescription}</span>
              </div>
            </div>
          </div>
        </Card>

        <UserTrendChart
          metrics={selectedMetrics}
          timeRange={timeRange}
          dateRange={getCustomDateRange()}
        />
      </div>
    </Card>
  )
} 